<template>
  <div>
    <FormPanel ref="formPanel" :list="formList" :cols="2" :collapse="false" :isSubmitBtn="false" @formChange="formChangeHandle"></FormPanel>
    <div style="text-align:center;">
      <el-button size="small" type="primary" @click="saveDialog">确定</el-button>
      <el-button size="small" type="primary" @click="closePage">取消</el-button>
    </div>
    <FilterTable
      ref="tableLabour"
      :columns="columnsLabour"
      height="auto"
      :maxHeight="710"
      columnsRef="roAssignModelLabourTable"
      :fetchapi="fetchapiLabour"
      :params="fetchParamsLabour"
      :isSelectColumn="true"
      :datakey="'rows'"
      :onRowSelectChange="SelectChange"
      :onSyncTableData="columns => (this.tableColumns = columns)"
      :onColumnsChange="columns => (this.columnsLabour = columns)"
    />
    <FilterTable
      ref="tablePart"
      :columns="columnsPart"
      height="auto"
      :maxHeight="710"
      columnsRef="roAssignModelPartTable"
      :fetchapi="fetchapiPart"
      :params="fetchParamsPart"
      :isSelectColumn="false"
      :datakey="'rows'"
      :onColumnsChange="columns => (this.columnsPart = columns)"
    />

    <BaseDialog :visible.sync="partDetail" :title="'发料明细'" destroyOnClose :containerStyle="{ height: 'calc(110% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <partDetailModel :roNo="this.roNo" @close="closeDialog" />
    </BaseDialog>

    <BaseDialog :visible.sync="completed" :title="'竣工'" destroyOnClose width="450px" :containerStyle="{ height: 'calc(110% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <completedModel :Mileage="this.roNo" @close="closeCompleted" />
    </BaseDialog>

    <div
      :style="{
        position: 'absolute',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'right'
      }"
    >
      <el-button size="small" type="primary" @click="partDetailClick">发料明细</el-button>
      <el-button size="small" type="primary" @click="deleteAssignClick">删除</el-button>
      <!-- <multiuse-button size="small" type="primary" :auth-list="auths" auth-mark="/repair/workManage/repairDispatch/Completion" @click="completedClick">竣工</multiuse-button> -->
      <el-button size="small" type="primary" @click="closePage">取消</el-button>
    </div>
  </div>
</template>

<script>
import { dictionary } from '@/utils/dictMixin';
import {
  queryRoLabourByRoNOss,
  queryFinished,
  queryRoRepairPartByTag,
  queryRoAssignByRoNOs,
  maintainRepairAssignComplete,
  selectWorkGroupDicts,
  deleteAssign,
  getWorkAllGroup,
  getAllUserByWorkGroupId
} from '@/api/repair/repairAssign/repairAssign';
import { searchRoleByCode, searchRoleByCodes } from '@/api/common/empSelect/index';
import partDetailModel from './partDetailModel';
import completedModel from './completedModel';
import addAssignModel from './addAssignModel';
import dictCode from '@/utils/dictCode';
import { authority } from '@/utils/authMixin';
import { findAllRepair } from '@/api/repair/basicParameters';
import pinyin, { STYLE_FIRST_LETTER } from '@/components/Pinyin/index';

// import { getWorkGroupNameByWorkId } from '@/api/repair/queryStatistics/queryAccounts';
export default {
  name: 'roAssignModel',
  components: {
    partDetailModel,
    completedModel,
    addAssignModel
  },
  mixins: [dictionary, authority],
  props: ['roNo', 'assignType'],
  data() {
    this.saveData = null;
    return {
      partDetail: false, // 发料明细页的显示
      LabourColumns: [], // 项目条数
      completed: false, // 竣工页面
      assignId: [], // 技师的获取
      fetchapiLabour: queryRoLabourByRoNOss,
      fetchParamsLabour: {},
      fetchParamsPart: {},
      fetchapiPart: queryRoRepairPartByTag,
      tableColumns: [],
      formList: this.assignType === 'group' ? this.createGroupTopFilterList() : this.createTopFilterList(),
      columnsLabour: this.createTableColumnsLabour(),
      columnsPart: this.createTableColumnsPart(),
      technicianRes: [], // 所有的技师
      allWorkGroup: [], // 所有的班组
      filterUsers: [], // 通过班组id获取到的技师
      copyFilterUsers: [], // 原始的技师数据 - 在filter时需要用
      technicianModel: ''
    };
  },
  created() {
    let roNo = this.roNo[0].RO_NO;
    this.fetchParamsLabour = Object.assign({}, { roNo: roNo }, { xhrAbort: false });
    this.fetchParamsPart = Object.assign({}, { roNo: roNo }, { xhrAbort: false });
    if (this.assignType === 'group') {
      // group-派工到班组，
      this.formList = this.createGroupTopFilterList();
    } else {
      this.formList = this.createTopFilterList();
    }
  },
  mounted() {
    this.serviceConsultant(); // 获取相关人员 技师，服务顾问...
    this.getLabour();
    if (this.assignType === 'group') {
      this.getWorkAllGroups(); // 获取所有班组
    }
  },
  methods: {
    // async getSystemDefaultValueInfo() {
    //   let resRepair = await findAllRepair();
    //   this.showGroup = String(resRepair.data['9505']) === '1' ? true : false; // group-派工到班组，major - 派工到人
    // },
    // 开启竣工
    async completedClick() {
      console.log(this.roNo, '前台带出的状态');
      if (this.roNo[0].COMPLETE_TAG == 10041002) {
        if (this.roNo[0].ASSIGN_STATUS == 80591003) {
          let res = await queryFinished(this.roNo[0].RO_NO).then(res => {
            if (res.data == '1') {
              this.$notify.error({ title: '提示信息', message: '此工单存在未入账配件，不能竣工 !' });
            } else {
              this.completed = true;
            }
          });
        } else {
          this.$notify.error({ title: '提示信息', message: '存在未派工的项目，不能竣工!' });
        }
      } else {
        this.$notify.error({ title: '提示信息', message: '该工单已竣工，不能重复竣工!' });
      }
    },
    // 关闭竣工
    closeCompleted() {
      this.completed = false;
      this.$emit('close', this.roNo[0]._uid);
    },
    // 选择项目
    SelectChange(row) {
      //  this.items.push(row.ITEM_ID);
      console.log('调用了...', row);
      let item = [];
      let str = "'";
      for (const val of row) {
        item.push(str + val.ITEM_ID + str);
      }
      if (row.length > 0) {
        this.LabourColumns = row;
      } else {
        this.LabourColumns = [];
        this.dataSource = [];
      }
    },
    // 删除项目
    async deleteAssignClick() {
      if (this.LabourColumns.length > 0) {
        let itemId = '';
        this.LabourColumns.forEach(x => {
          if (x.ITEM_ID) itemId += x.ITEM_ID + ',';
        });
        let json = {
          roNo: this.roNo[0].RO_NO,
          itemId: itemId
          // assignId: this.assignId.join()
        };
        let res = await deleteAssign(json).then(() => {
          this.fetchParamsLabour = Object.assign({}, this.fetchParamsLabour); // 刷新表格
        });
      } else {
        this.$notify.error({ title: '提示信息', message: '请先选数据!' });
      }
    },
    // 发料明细页显示
    partDetailClick() {
      this.partDetail = true;
    },
    // 发料明细页关闭
    closeDialog() {
      this.partDetail = false;
    },
    async getWorkAllGroups() {
      let res = await getWorkAllGroup();
      console.log(res.data, 'getWorkAllGroup');
      this.banzuList = res.data.map(x => ({ value: x.WORKGROUP_CODE, text: `${x.WORKGROUP_CODE} - ${x.WORKGROUP_NAME}`, Id: x.WORKGROUP_ID }));
      this.formList.find(x => x.fieldName === 'workGroupCode').itemList = this.banzuList;
      console.log(this.banzuList, 'this.banzuList');
      // this.formList.find(x => x.fieldName === 'workGroupCode').itemList = this.allWorkGroup; // 车间需要根据id获取名称
    },
    async resetTechnician(val) {
      let res = await getAllUserByWorkGroupId({ workGropId: val, userId: '', sign: 'work' });
      if (res.resultCode === 200) {
        let personList = res.data.map(x => ({ value: x.USER_ID, text: `${x.EMPLOYEE_NAME}` }));
        this.filterUsers = personList;
        this.copyFilterUsers = [...personList];
        console.log('personList', personList);
      }
    },
    filterMethod(queryString) {
      console.log(queryString);
      if (!queryString.length) {
        this.filterUsers = this.copyFilterUsers;
        return;
      }

      let res = [];
      this.filterUsers = this.copyFilterUsers.filter(x => {
        // 拼音匹配
        const pyStr = _.flatten(pinyin(x.text, { style: STYLE_FIRST_LETTER })).join('');
        // 字符串匹配

        return pyStr.toLowerCase().includes(queryString.toLowerCase()) || x.text.includes(queryString);
      });
      console.log(this.filterUsers);
    },
    createTopFilterList() {
      return [
        {
          type: 'SELECT',
          label: '派工技师',
          fieldName: 'technician',
          filterable: true,
          placeholder: '请选择派工技师',
          filterable: true,
          itemList: [],
          rules: [{ required: true, message: '请选择派工技师', trigger: 'blur' }],
          change: val => {}
        },
        {
          type: 'SELECT',
          label: '派工工位',
          filterable: true,
          fieldName: 'positionCode',
          placeholder: '请选择派工工位',
          itemList: []
        },
        {
          type: 'INPUT_NUMBER',
          label: '工时系数',
          fieldName: 'workHour',
          placeholder: '请输入工时系数',
          initialValue: 100,
          style: { width: 'calc(60% - 90px)' },
          descOptions: {
            content: '%'
          },
          rules: [{ pattern: /^([1-9]\d{0,3}|9999)$/, message: '请输入正整数(最大四位)' }]
        },
        // {
        //   type: 'SELECT',
        //   label: '检验人',
        //   filterable: true,
        //   fieldName: 'checker',
        //   placeholder: '请选择检验人',
        //   filterable: true,
        //   itemList: []
        // },
        {
          type: 'SELECT',
          label: '试车员',
          fieldName: 'testDriver',
          placeholder: '请选择试车员',
          itemList: []
        }
      ];
    },
    createGroupTopFilterList() {
      return [
        {
          type: 'SELECT',
          label: '班组',
          fieldName: 'workGroupCode', // intentSeriesId
          filterable: true,
          itemList: [],
          change: (val, text) => {
            this.technicianModel = '';
            if (val) {
              const pId = this.banzuList.find(x => x.value === val).Id;
              console.log('班组pId', pId);
              if (pId) {
                this.resetTechnician(pId);
              }
            }
            if (!val) {
              this.filterUsers = [];
              this.copyFilterUsers = [];
            }
          }
        },
        {
          type: 'SELECT',
          label: '派工技师',
          fieldName: 'technician',
          placeholder: '请选择派工技师或班组',
          filterable: true,
          disabled: true,
          itemList: [],
          render: props => {
            return (
              <div>
                <el-select v-model={this.technicianModel} placeholder="请选择" filterable filter-method={this.filterMethod}>
                  {this.filterUsers.map(x => {
                    return <el-option value={x.value} key={x.value} label={x.text}></el-option>;
                  })}
                </el-select>
                )
              </div>
            );
          }
        },
        {
          type: 'SELECT',
          label: '派工工位',
          fieldName: 'positionCode',
          filterable: true,
          placeholder: '请选择派工工位',
          itemList: []
        },
        {
          type: 'INPUT_NUMBER',
          label: '工时系数',
          fieldName: 'workHour',
          placeholder: '请输入工时系数',
          initialValue: 100,
          style: { width: 'calc(60% - 90px)' },
          descOptions: {
            content: '%'
          },
          rules: [{ pattern: /^([1-9]\d{0,3}|9999)$/, message: '请输入正整数(最大四位)' }]
        }
        // {
        //   type: 'SELECT',
        //   label: '检验人',
        //   fieldName: 'checker',
        //   filterable: true,
        //   placeholder: '请选择检验人',
        //   filterable: true,
        //   itemList: []
        // }
      ];
    },
    createTableColumnsLabour() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        // {
        //   title: '检查结果',
        //   dataIndex: 'TROUBLE_DESC',
        //   sorter: true,
        //   filter: true,
        //   width: 110,
        //   filterType: 'input'
        // },
        {
          title: '故障原因',
          dataIndex: 'TROUBLE_CAUSE',
          sorter: true,
          filter: true,
          width: 110,
          filterType: 'input'
        },
        {
          title: '是否派工',
          dataIndex: 'ASSIGN_TAG',
          sorter: true,
          filter: true,
          width: 110,
          filterType: 'checkbox',
          filterItems: this.createDictList(1004),
          render: props => {
            return <span>{this.createDictText(props.row.ASSIGN_TAG, '1004')}</span>;
          }
        },
        {
          title: '是否委外',
          dataIndex: 'CONSIGN_EXTERIOR',
          dictItems: this.createDictList(1004),
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList(1004)
        },
        {
          title: '维修项目代码',
          dataIndex: 'LABOUR_CODE',
          sorter: true,
          filter: true,
          width: 140,
          filterType: 'input'
        },
        {
          title: '维修项目名称',
          dataIndex: 'LABOUR_NAME',
          sorter: true,
          filter: true,
          width: 200,
          filterType: 'input'
        },
        {
          title: '工时费',
          dataIndex: 'LABOUR_AMOUNT',
          sorter: true,
          filter: true,
          width: 110,
          filterType: 'input',
          summation: true,
          precision: 2
        },
        {
          title: '派工工时',
          dataIndex: 'ASSIGN_LABOUR_HOUR',
          sorter: true,
          filter: true,
          width: 110,
          filterType: 'input',
          summation: true,
          precision: 2
        },
        {
          title: '责任技师',
          dataIndex: 'TECHNICIAN_NAME',
          sorter: true,
          filter: true,
          width: 110,
          editable: false,
          editType: 'select',
          editItems: [],
          filterType: 'input'
        },
        {
          title: '收费区分',
          dataIndex: 'CHARGE_PARTITION_CODE',
          sorter: true,
          filter: true,
          width: 110,
          filterType: 'input'
        },
        {
          title: '是否不修',
          dataIndex: 'NEEDLESS_REPAIR',
          sorter: true,
          filter: true,
          width: 110,
          filterType: 'checkbox',
          filterItems: this.createDictList(1004),
          render: props => {
            return <span>{this.createDictText(props.row.NEEDLESS_REPAIR, '1004')}</span>;
          }
        },
        {
          title: '备注',
          dataIndex: 'REMARK',
          sorter: true,
          filter: true,
          width: 110,
          filterType: 'input'
        }
      ];
    },
    createTableColumnsPart() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '仓库',
          dataIndex: 'STORAGE_NAME',
          sorter: true,
          filter: true,
          width: 110,
          filterType: 'input'
        },
        {
          title: '配件代码',
          dataIndex: 'PART_NO',
          sorter: true,
          filter: true,
          width: 110,
          filterType: 'input'
        },
        {
          title: '配件名称',
          dataIndex: 'PART_NAME',
          sorter: true,
          filter: true,
          width: 110,
          filterType: 'input'
        },
        {
          title: '配件数量',
          dataIndex: 'PART_QUANTITY',
          sorter: true,
          filter: true,
          width: 110,
          filterType: 'input',
          summation: true
        },
        {
          title: '计量单位',
          dataIndex: 'UNIT_NAME',
          sorter: true,
          filter: true,
          width: 110,
          filterType: 'input'
        },
        {
          title: '配件销售单价',
          dataIndex: 'PART_SALES_PRICE',
          sorter: true,
          filter: true,
          width: 200,
          filterType: 'input',
          summation: false,
          precision: 2
        },
        {
          title: '配件销售金额',
          dataIndex: 'PART_SALES_AMOUNT',
          sorter: true,
          filter: true,
          width: 200,
          filterType: 'input',
          summation: true,
          precision: 2
        },
        {
          title: '领料人',
          dataIndex: 'RECEIVER',
          sorter: true,
          filter: true,
          editable: false,
          editType: 'select',
          editItems: [],
          filterType: 'input'
        },
        {
          title: '收费区分',
          dataIndex: 'CHARGE_PARTITION_CODE',
          sorter: true,
          filter: true,
          filterType: 'input'
        }
      ];
    },
    // 表单提交
    formChangeHandle(val) {
      this.saveData = val;
    },
    async getLabour() {
      let res = await queryRoLabourByRoNOss({ roNo: this.roNo[0].RO_NO });
      let itemId = res.data.rows[0].ITEM_ID;
      let ress = await queryRoAssignByRoNOs(itemId);
      ress.data.rows.forEach(x => {
        this.assignId.push(x.TECHNICIAN);
      });
      return res;
    },
    async getPart() {
      return await queryRoRepairPartByTag(this.roNo[0].RO_NO);
    },
    // 售前人员接口数据
    async serviceConsultant() {
      let technician = { role: dictCode.TECHNICIAN }; // 指定技师
      let testDrive = { role: dictCode.TEST_DRIVE };
      let examinationClerk = { role: dictCode.EXAMINATION_CLERK };
      let materiel = { positionCode: dictCode.MATERIAL_AVAILABLE }; // 领料人
      const technicianRes = await searchRoleByCodes(technician);
      const testDriveRes = await searchRoleByCode(testDrive);
      const examinationClerkRes = await searchRoleByCode(examinationClerk);
      const materielSend = await searchRoleByCodes(materiel);
      const assignWorkType = await selectWorkGroupDicts();

      this.technicianRes = [...technicianRes.data.map(x => ({ text: x.employeeName, value: x.userId + '' }))];
      console.log(this.technicianRes, 'this.technicianRes');
      this.columnsLabour.find(item => item.dataIndex === 'TECHNICIAN_NAME').editItems = materielSend.data.map(x => ({ text: x.employeeName, value: x.userId + '' }));
      if (this.assignType !== 'group') {
        this.formList.find(item => item.fieldName === 'technician').itemList = [...this.technicianRes];
      }
      // this.formList.find(item => item.fieldName === 'checker').itemList = examinationClerkRes.data.map(x => ({ text: x.employeeName, value: x.userId }));
      this.formList.find(item => item.fieldName === 'testDriver').itemList = examinationClerkRes.data.map(x => ({ text: x.employeeName, value: x.userId }));
      this.formList.find(item => item.fieldName === 'positionCode').itemList = assignWorkType.data.map(x => ({ text: x.LABOUR_POSITION_NAME, value: x.LABOUR_POSITION_CODE }));
      this.columnsPart.find(item => item.dataIndex === 'RECEIVER').editItems = materielSend.data.map(x => ({ text: x.employeeName, value: x.userId + '' }));
    },
    async saveDialog() {
      if (this.isLoading) return;
      this.isLoading = true;
      this.saveData = null;
      this.$refs.formPanel.SUBMIT_FORM();
      if (this.saveData != null) {
        let obj = {
          // workHour: this.formList.find(item => item.fieldName === 'workHour').initialValue,
          // positionCode: this.formList.find(item => item.fieldName === 'positionCode').initialValue,
          // checker: this.formList.find(item => item.fieldName === 'checker').initialValue,
          // testDriver: this.formList.find(item => item.fieldName === 'testDriver').initialValue,
          ...this.saveData,
          roNo: this.roNo[0].RO_NO,
          table: this.tableColumns,
          id: '2'
        };
        if (this.assignType === 'group') {
          obj.technician = this.technicianModel;
        }
        console.log(obj);
        await maintainRepairAssignComplete(obj).then(res => {
          this.isLoading = false;
          if (res.resultCode === 200) {
            this.$notify({ title: '提示信息', message: '派工操作成功', type: 'success' });
            this.$emit('close', this.roNo[0]._uid);
          }
        });
      } else {
        this.isLoading = false;
        // return this.$notify.warning({ title: '提示信息', message: '有校验信息未通过' });
      }
    },
    closePage() {
      this.$emit('close', this.roNo[0]._uid);
    }
  }
};
</script>
